#include "parse_history.h"
#include <map.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

smap *his = NULL;

void history_release( void *h )
{
    exp_tree_release( ((lex_his*)h)->e );
    free( h );
}

void init_history( )
{
    his = im_create();
}

void uninit_history( )
{
    if( his != NULL )
    {
        im_for_each( his, history_release );
        im_destroy( his );
    }
}

int add_parse( token *key, const lex_his *lex )
{
    lex_his *lh = find_parse( key );
    if( lh == NULL )
    {
        lh = (lex_his*)malloc( sizeof(lex_his) );
        memset( lh, 0, sizeof(lex_his) );
    }
    else
    {
        exp_tree_release( lh->e );
    }
    lh->e = lex->e;
    lh->until = lex->until;
    add_ref( lh->e );
    im_insert( his, (int64)key, (void*)lh );
    return 0;
}

lex_his* find_parse( token *key )
{
    lex_his *lh;
    im_find( his, (int64)key, (void**)&lh );
    if( lh )
        add_ref( lh->e );
    return lh;
}
